---@class AARTanker
AARTanker = {}
--[[
    单位换算:

    1NM = 1852 m = 6076.115 ft

    1 m = 3.279 ft
    1 ft = 0.305 m

    1 knot = 0.514 m/s
    1 m/s = 1.944 knots

    1 kg = 2.205 lbs
]]

--[[
    TODO:
    1. 无线电菜单呼叫加油机
    2. 长时间不使用的加油机自动回收(删除并释放无线电|塔康|空域)

]]
---@class Vec2 {x,y}
---@field x number horz north
---@field y number horz west

---@class Vec3 {x,y,z}
---@field x number horz north
---@field y number vort
---@field z number horz west

do
---========== Config ==========
    local DebugMode = false

    -- Default settings.
    local DEFAULT_TANKER_CAS = 270/1.944 --m/s, around 270 knots
    local DEFAULT_TANKER_CRUISE_CAS = 380/1.944 --m/s, around 380 knots
    local DEFAULT_TRACK_LENGTH = 50*1852 --m, around 50NM
    local DEFAULT_TRACK_HEADING = 270
    local DEFAULT_RADIO_POWER = 10

    local BINGO_FUEL_PERCENTAGE = 0.15 -- tanker bingo fuel percentage. In current version, even unlimited fuel will bingo due to refueling.

    -- Rearm airfield
    -- local DEFAULT_REARM_AIRFIELD = 'Krymsk' -- Airfield name for tanker to rearm, nil for auto select nearest airfield.

    --Airspace settings.
    local AIRSPACE_ROW_MAX = 2 --most tankers in a row
    local AIRSPACE_COLUMN_MAX = 4 --most tankers in a column
    local AIRSPACE_SPACING = {
        vert = 3500*0.305, --m, about 5000ft
        horz = 16*1852, --m about 8NM
    }
    local AIRSPACE_BASE_POINT = {
        x = -159353,
        y = 8000*0.305, --m, about 5000ft,
        z = 402581,
    }

    local ORBIT_TYPES = {
        race_track = 'Race-Track',
        circle = 'Circle'
    }

    local TankerTypeNames = {
        IL78M = 'IL-78M',
        KC135 = 'KC-135',
        KC135MPRS = 'KC135MPRS',
        KC130 = 'KC130',
        S3B = 'S-3B Tanker',
    }

    local CARRIER_TANKER = {
        [TankerTypeNames.S3B] = true,
    }
    local TankerCallsigns = {
        [TankerTypeNames.KC135] = {
            id = 1,
            name = 'Texaco',
            index = {},
        },
        [TankerTypeNames.S3B] = {
            id = 3,
            name = 'Shell',
            index = {},
        },
        default = {
            id = 2,
            name = 'Arco',
            index = {},
        },
    }
    local NameIndexTable = {}

---========= Config end =======

--- 私有变量
    local AllTankers = {}
    local Airspace = {}
    local EventHandlerPool = {}

--- 私有函数
    --Debug function
    local function Debug(msg)
        if not DebugMode then return end
        Utils.Debug(msg)
    end

    -- Init airspace boxeses.
    local function initAirspaceBoxeses()
        Debug('AARTanker - initAirspaceBoxeses')

        -- Clear all boxes first.
        Airspace = {}

        local AGL = land.getHeight({x=AIRSPACE_BASE_POINT.x,y=AIRSPACE_BASE_POINT.z})
        if AIRSPACE_BASE_POINT.y-AIRSPACE_SPACING.vert < AGL then
            AIRSPACE_BASE_POINT.y = AIRSPACE_BASE_POINT.y + AIRSPACE_SPACING.vert
        end

        local basePoint = Utils.deepCopy(AIRSPACE_BASE_POINT)

        for i=1,AIRSPACE_ROW_MAX,1 do
            for j=1,AIRSPACE_COLUMN_MAX,1 do

                local box = {
                    userName = nil,
                    spawnPoint = Utils.deepCopy(basePoint),
                    altitude = basePoint.y,
                }

                table.insert(Airspace,box)

                local alt = basePoint.y
                local angle = DEFAULT_TRACK_HEADING+135
                if angle > 360 then
                    angle = angle - 360
                end

                basePoint = Utils.makeVec3(Utils.vecTranslate(basePoint,angle,math.sqrt(2)*AIRSPACE_SPACING.horz))
                basePoint.y = alt + AIRSPACE_SPACING.vert
            end

            basePoint = AIRSPACE_BASE_POINT
            basePoint.y = AIRSPACE_BASE_POINT.y + AIRSPACE_SPACING.vert*i
        end 
        table.sort(Airspace,function (a,b)
            return a.altitude<b.altitude
        end)
    end

    --@param string groupName
    --@return vec3 for startPoint
    local function registerAirspace(params)
        if not params.groupName then return false end
        if type(params.groupName)~='string' then return false end
        
        Debug('AARTanker - registerAirspace: groupName:'..params.groupName)

        if not Airspace or Utils.getTableSize(Airspace)<1 then
            initAirspaceBoxeses()
        end

        for i, airspaceBox in ipairs(Airspace) do
            if airspaceBox.userName and params.groupName == airspaceBox.userName then
                Debug('AARTanker - registerAirspace: '..params.groupName..' already have registered airspace.')
                Debug(airspaceBox.spawnPoint)
                return airspaceBox.spawnPoint
            end

            if not airspaceBox.userName then
                airspaceBox.userName = params.groupName
                Debug('AARTanker - registerAirspace: assign altitude: '..airspaceBox.altitude..' to '..params.groupName)
                return airspaceBox.spawnPoint
            end
        end

        Debug('AARTanker - registerAirspace: No airspace available.')
        return false
    end

    --@param string groupName for the airspace userName whom to deregister.
    --@return boolean result of deregistering airspace.
    local function deregisterAirspace(groupName)
        if not groupName then return false end
        if type(groupName)~='string' then return false end

        local debugMsg = 'AARTanker - deregisterAirspace: '
        for i, airspaceBox in ipairs(Airspace) do
            if groupName == airspaceBox.userName then
                airspaceBox.userName = nil

                debugMsg = debugMsg..groupName..' deregister successful.'
                Debug(debugMsg)
                return true
            end
        end

        debugMsg = debugMsg..groupName..' deregister failed, group name not found.'
        Debug(debugMsg)
        return false
    end

    --@param number for expect CAS.
    --@param table vec2|vec3 point.
    --@return number TAS for spawn speed setting in m/s 1 knot = 0.51444 m/s.
    local function getTASByCAS(expectCAS,unitPoint)
        if not expectCAS or type(expectCAS)~='number' then return end
        if not unitPoint or not unitPoint.z then return end

        local temperature, pressure = atmosphere.getTemperatureAndPressure(unitPoint)

        local R = 287
        local rho0 = 1.225
        local rho = pressure/(R * temperature)

        local TAS = expectCAS / math.sqrt(rho / rho0)

        local debugMsg = 'AARTanker - getTASByCAS: expectCAS: '..expectCAS..' return TAS: '..TAS
        Debug(debugMsg)

        return TAS
    end

    --@return number newHeading for assigned race-track heading.
    local function getDefaultTrackHeading()
        return DEFAULT_TRACK_HEADING
    end

    --@return boolean if the typeName matchs TankerTypeNames.
    local function isTankerTypeName(typeName)
        for _,type in pairs(TankerTypeNames) do
            if typeName == type then
                return true
            end
        end

        return false
    end

    ---@param vec Vec2|Vec3
    ---@param tCoalition number|nil coalition.side
    ---@return Airbase
    local function getNearestAirfield(vec,tCoalition,isCarrierTanker)
        if not vec then return end
        tCoalition = tCoalition or coalition.side.BLUE

        local airbaseList = coalition.getAirbases(tCoalition)

        local minDistance = math.huge
        local result = nil
        for i,airbase in ipairs(airbaseList) do
            if isCarrierTanker then
                if airbase:getDesc().attributes["Aircraft Carriers"] or airbase:getDesc().attributes.AircraftCarrier then
                    local distance = Utils.get3DDist(airbase:getPoint(),Utils.makeVec3(vec))
                    if distance < minDistance then
                        result = airbase
                        minDistance = distance
                    end
                end
            end

            if not isCarrierTanker then
                local distance = Utils.get3DDist(airbase:getPoint(),Utils.makeVec3(vec))
                if distance < minDistance then
                    result = airbase
                    minDistance = distance
                end
            end
        end

        return result
    end

    ---@param param.speed number/nil speed as TAS.
    ---@param param.typeName string|nil type name of this tanker.
    ---@return table route table
    local function getOrbitRoute(params)
        local debugMsg = 'AARTanker - getOrbitRoute: '

        -- Find available airspace
        params.startPoint = registerAirspace(params)
        Debug('startPoint:')
        Debug(params.startPoint)
        local point = params.startPoint
        if not point then
            debugMsg = debugMsg..' can not register airspace.'
            Debug(debugMsg)
            return
        end

        local speed = params.speed or DEFAULT_TANKER_CAS
        speed = getTASByCAS(speed,point)
        params.speed = speed
        local orbitType = ORBIT_TYPES.race_track 
        local trackLength = DEFAULT_TRACK_LENGTH
        local altitude = point.y
        
        debugMsg = debugMsg..'\n Input values:'..'\n speed: '..(speed/0.514)..'knots\n orbitType: '..orbitType..
                             '\n trackLength: '..(trackLength/1852)..'NM\n altitude: '..(altitude/0.305)..'ft\n'
        Debug(debugMsg)

        ---Make route
        local route = {points = {}}
        for i=1,2,1 do
            route.points[i] = {
                ["alt"] = altitude,
                ["action"] = "Turning Point",
                ["type"] = "Turning Point",
                ["alt_type"] = "BARO",
                ["speed"] = speed,
                ["y"] = point.z or point.y,
                ["x"] = point.x,
            }

            point = Utils.vecTranslate(point,getDefaultTrackHeading(),trackLength)
            -- point = Utils.makeVec3(point)
        end

        route.points[1]['task'] = {
            ["id"] = "ComboTask",
            ["params"] = 
            {
                ["tasks"] = 
                {
                    [1] = {
                        ["enabled"] = true,
                        ["auto"] = true,
                        ["id"] = "Tanker",
                        ["number"] = 1,
                        ["params"] = {},
                    },
                    --set reaction to threat: passive defence.
                    [2] = {
                        ["id"] = "WrappedAction",
                        ["params"] = {
                            ["action"] = {
                                ["id"] = "Option",
                                ["params"] = {
                                    ["name"] = 1,
                                    ["value"] = 1,
                                },
                            }
                        },
                    },
                    -- set Prohibit WP Pass Report
                    [3] = {
                        ["id"] = "WrappedAction",
                        ["params"] = {
                            ["action"] = {
                                ["id"] = "Option",
                                ["params"] = {
                                    ["name"] = AI.Option.Air.id.PROHIBIT_WP_PASS_REPORT,
                                    ["value"] = true,
                                },
                            }
                        },
                    },
                    -- set immortal.
                    [4] = {
                        ["id"] = "WrappedAction",
                        ["params"] = {
                            ["action"] = {
                                ["id"] = "SetImmortal",
                                ["params"] = {
                                    ["value"] = true,
                                },
                            }
                        },
                    },
                    -- set unlimited fuel.
                    [5] = {
                        ["id"] = "WrappedAction",
                        ["params"] = {
                            ["action"] = {
                                ["id"] = "SetUnlimitedFuel",
                                ["params"] = {
                                    ["value"] = true,
                                    -- ["value"] = false,
                                },
                            }
                        },
                    },
                    [6] = {
                        -- ["enabled"] = true,
                        -- ["auto"] = false,
                        ["id"] = "Orbit",
                        -- ["number"] = 1,
                        ["params"] = 
                        {
                            ["altitudeEdited"] = true,
                            ["pattern"] = orbitType,
                            ["speed"] = speed,
                            ["altitude"] = altitude,
                            ["speedEdited"] = true,
                        }, -- end of ["params"]
                    },
                }, -- end of ["tasks"]
            }, -- end of ["params"]
        } -- end of ["task"]

        return route
    end

    --@param string groupName
    --@param string typeName
    --@param number/nil speed as TAS
    --@return table DCS.Group
    local function spawnTanker(params)
        if not params or not params.typeName or not params.groupName then return end

        local debugMsg = 'AARTanker - spawnTanker: '

        local spawnData = {}
        spawnData.name = params.groupName
        spawnData.task = "Refueling"
        spawnData.route = getOrbitRoute(params)
        spawnData.units = {
            [1] = {
                name = params.groupName..'-1',                                     
                type = params.typeName,
                x = params.startPoint.x,
                y = params.startPoint.z,
                alt = params.startPoint.y,
                alt_type = 'BARO',
                speed = params.speed,
                payload = {
                    ["pylons"] = {},
                    ["fuel"] = math.huge,
                }
            }
        }

        --set callsign
        local callsignTable = TankerCallsigns[params.typeName]
        if not callsignTable then 
            callsignTable = TankerCallsigns.default
        end
        local index = ''
        local indexTable = callsignTable.index
        for i=1,#indexTable+1,1 do
            local group = indexTable[i]
            if not group or type(group)=='string' then
                index = i
                indexTable[i] = params.groupName
                break
            end
        end

        spawnData.units[1]['callsign'] = {
            name = callsignTable.name..index..'1',
            [1] = callsignTable.id,
            [2] = index,
            [3] = 1,
        }

        local group = coalition.addGroup(country.id.CJTF_BLUE,Group.Category.AIRPLANE,spawnData)
        if not group then
            debugMsg = debugMsg..' can not spawn group. spawnData:'
            Debug(debugMsg)
            Debug(spawnData)
        end
        indexTable[index] = group
        return group
    end

    --- Get nearest tanker, 3D speace.
    ---@param vec Vec2|Vec3
    ---@return AARTanker
    local function getNearestTanker(vec)
        if not vec then return end

        local vec = Utils.makeVec3(vec)

        local result = nil
        local minDistance = math.huge
        for name, tankerObj in pairs(AllTankers) do
            local tankerUnit = Utils.getFirstUnit(tankerObj.group,true)
            if not tankerUnit then
                tankerObj:Remove()
                return
            end

            local tankerPoint = tankerUnit:getPoint()
            local distance = Utils.get3DDist(tankerPoint,vec)
            if distance < minDistance then
                minDistance = distance
                result = tankerObj
            end
        end

        return result
    end

--- 公有函数
    --@param string|table typeName|params for spawn units
    --@param string/nil groupName, default is "[typeName]-[tankerID]"
    --@param number/nil speed for CAS|IAS, default 270knots.
    --@param string/nil callSign for TACAN callSign, can be nil.
    --@param number/nil TACAN_channel for TACAN channel, nil for auto choose.
    --@param number/nil TACAN_mode for TACAN mode(X or Y), default X.
    --@param number/nil radio_channel for radio channel, nil for auto choose.
    --@param number/nil radio_mode for radio modulation, default AM(0).
    --@return table AARTanker object.
    function AARTanker:New(params)
        Debug('AARTanker - New: params:')
        Debug(params)
        if not params then return end

        -- If user only gives a string
        if type(params)=='string' then
            -- If params is groupName
            local group = Group.getByName(params)
            if group and group.isExist and group:isExist() then
                local groupName = params
                params = {}
                params.groupName = groupName 
                local unit = group:getUnit(1)
                if unit and unit:isExist() and unit:getLife()<1 then
                    params.typeName = unit:getTypeName()
                end
            end

            if not group or not group.isExist or not group:isExist() then
                local tTypeName = params
                params = {}
                params.typeName = tTypeName
            end
        end

        if not params.typeName and not params.groupName then return end
        if not isTankerTypeName(params.typeName) then return end
        if params.groupName and type(params.groupName)~='string' then return end

        -- if not groupName then set a default name.
        if not params.groupName or type(params.groupName)~='string' then
            NameIndexTable[params.typeName] = NameIndexTable[params.typeName] or {}
            
            for i=1,#NameIndexTable[params.typeName]+1,1 do
                if not NameIndexTable[params.typeName][i] or not Group.getByName(NameIndexTable[params.typeName][i]) then
                    params.groupName = params.typeName..'-'..i
                    NameIndexTable[params.typeName][i] = params.groupName
                end
            end
        end
        
        local debugMsg = 'AARTanker - New: '

        if AllTankers[params.groupName] then
            AllTankers[params.groupName]:Remove()
        end

        local group = Group.getByName(params.groupName)

        local obj = {}
        obj.type = params.typeName
        obj.name = params.groupName
        obj.group = group or spawnTanker(params)

        -- set radio.
        obj.radio = params.radio_channel
        obj.radio_mode = params.radio_mode

        -- set TACAN.
        obj.TACAN_mode = params.TACAN_mode or 'X' -- X or Y, default X.
        obj.TACAN_mode = string.upper(obj.TACAN_mode)

        obj.TACAN = params.TACAN_channel
        obj.callSign = params.callSign
        obj.TACAN_On = false

        setmetatable(obj, self)
        self.__index = self

        timer.scheduleFunction(function (tanker)
            tanker:init()
        end,obj,timer.getTime() + 5)

        -- 事件监听AARTanker移除事件
        local ev = {
            tankerObj = obj
        }
        function ev:onEvent(event)
            -- 如果加油机被摧毁
            if event.id == world.event.S_EVENT_DEAD then
            
                local obj = event.initiator
                if not obj or not obj.getName or not obj.getGroup then return end

                local group = obj:getGroup()
                if not group or not group:isExist() or not group.getName then return end

                local tanker = ev.tankerObj
                if group:getName() == tanker.name then
                    tanker:Remove()
                end
            end

            -- 每次停止加油检查加油机剩余油量, 少于 BINGO_FUEL_PERCENTAGE 则为bingo
            if event.id == world.event.S_EVENT_REFUELING_STOP then
                local obj = event.initiator
                if not obj or not obj.getName or not obj.getGroup then return end
                
                local tCoalition = obj:getCoalition()

                local nearestTanker = getNearestTanker(obj:getPoint())
                if not nearestTanker then return end

                local tankerUnit = Utils.getFirstUnit(nearestTanker.group,true)
                if not tankerUnit then return end

                if tankerUnit:getFuel() <= BINGO_FUEL_PERCENTAGE then
                    local SetUnlimitedFuel = { 
                        id = 'SetUnlimitedFuel', 
                        params = { 
                            value = false 
                        } 
                    }

                    local controller = tankerUnit:getController()
                    if not controller then return end

                    controller:setCommand(SetUnlimitedFuel)

                    local msg = string.format(Localizations:translate('Tanker %s bingo fuel, RTB. New tanker will be spawned after it landed.','cn'),nearestTanker.name)
                    trigger.action.outTextForCoalition(tCoalition,msg,10)
                end
            end

            -- 如果加油机降落, 则刷新新的加油机
            if event.id == world.event.S_EVENT_ENGINE_SHUTDOWN then
                local obj = event.initiator
                if not obj or not obj.getName or not obj.getGroup then return end

                local group = obj:getGroup()
                if not group or not group:isExist() or not group.getName then return end

                local tanker = ev.tankerObj
                if group:getName() == tanker.name then
                    local typeName = tanker.type
                    tanker:Remove()
                    
                    timer.scheduleFunction(function (params) 
                        AARTanker:New(params.typeName)
                        local msg = string.format(Localizations:translate('New %s tanker has spawned. Info can be found at F10 map','cn'),params.typeName)
                        trigger.action.outTextForCoalition(params.tCoalition,msg,10)
                    end,{typeName = typeName,tCoalition = group:getCoalition()},timer.getTime()+5)
                end
            end
        end
        world.addEventHandler(ev)
        EventHandlerPool[obj.name] = ev

        AllTankers[obj.name] = obj
        return obj
    end

    function AARTanker:Remove()
        if not self.name or not AllTankers[self.name] then return end

        -- deregister radio
        if RadioManager then
            RadioManager.deregisterChannel(self.name)
        end
        -- deregister TACAN
        if TACANManager then
            TACANManager.deregisterChannel(self.name)
        end

        -- Remove DCS.Group is isexist.
        if self.group and self.group:isExist() then
            self.group:destroy()
        end
        
        -- deregister Airspace
        deregisterAirspace(self.name)

        -- 移除事件监听器
        if EventHandlerPool[self.name] then
            world.removeEventHandler(EventHandlerPool[self.name])
            EventHandlerPool[self.name] = nil
        end
        
        AllTankers[self.name] = nil
    end

    function AARTanker:init(params)
        params = params or {}
        params.groupName = self.name
        params.speed = params.speed or DEFAULT_TANKER_CAS

        self:setTankerMission(params)

        self:setRadio()
        self:setTACAN()
    end

    --@param number/nil speed as TAS
    function AARTanker:setTankerMission(params)
        local Mission = {
            id = 'Mission',
            params = {}
        }

        Mission.params.route = getOrbitRoute(params)

        if not self.group or not self.group:isExist() then
            self:Remove()
            return
        end

        local controller = self.group:getController()
        if not controller then
            self:Remove()
            return
        end

        controller:setTask(Mission)
    end

    --@param number/nil radio_channel
    --@param number/nil radio_mode for radio modulation, default AM(0).
    function AARTanker:setRadio(params)
        params = params or {}
        local frequency = params.radio_channel or self.radio
        if RadioManager then
            frequency = RadioManager.registerChannel({userName = self.name,freq = frequency,reusable = false})
        end
        if not frequency then return end

        local power = params.power or DEFAULT_RADIO_POWER
        local modulation = params.modulation or self.radio_mode or radio.modulation.AM

        local group = self.group
        if not group or not group:isExist() then
            self:Remove()
            return
        end

        local unit = group:getUnit(1)
        if not unit then 
            self:Remove()
            return
        end  

        local controller = unit:getController()
        if not controller then return end

        local SetFrequency = { 
            id = 'SetFrequencyForUnit', 
            params = { 
                frequency = frequency, 
                modulation = modulation, 
                power = power, 
                unitId = unit:getID(),
            } 
        }
        controller:setCommand(SetFrequency)
        self.radio = frequency
    end

    function AARTanker:setTACAN(vars)
        vars = vars or {}
        local group = self.group
        if not group or not group:isExist() then
            self:Remove()
            return
        end

        local unit = group:getUnit(1)
        if not unit then 
            self:Remove()
            return
        end  

        local controller = unit:getController()
        if not controller then return end

        self.TACAN = vars.channel or self.TACAN
        self.TACAN_mode = vars.mode or self.TACAN_mode

        if TACANManager then
            local params = {}
            params.userName = self.name
            params.channel = self.TACAN
            params.mode = self.TACAN_mode
            params.callSign = self.callSign

            self.TACAN = TACANManager.registerChannel(params)
        end

        local ActivateBeacon ={
            id = 'ActivateBeacon',
            params = {
                type = 4,
                system = 4,
                callsign = self.callSign,
                channel = self.TACAN,
                modeChannel = self.TACAN_mode,
                bearing = true,
                frequency = Utils.TACANToFrequency(self.TACAN, self.TACAN_mode),
            }
        }

        controller:setCommand(ActivateBeacon)
        self.TACAN_On = true

    end

    --@param number CAS
    function AARTanker:setSpeed(CAS)
        if not self.group or not self.group:isExist() then
            self:Remove()
            return
        end

        local controller = self.group:getController()
        if not controller then
            self:Remove()
            return
        end

        local unit = self.group:getUnit(1)
        if not unit or not unit:isExist() or unit:getLife()<1 then 
            self:Remove()
            return
        end

        local TAS = getTASByCAS(CAS,unit:getPoint())
        controller:setSpeed(TAS)
    end

    function AARTanker.DebugMode()
        return DebugMode
    end

    function AARTanker.getTankerTypeNames()
        return Utils.deepCopy(TankerTypeNames)
    end

    function AARTanker.setAirspaceBasePoint(newPoint)
        AIRSPACE_BASE_POINT.x = newPoint.x
        AIRSPACE_BASE_POINT.z = newPoint.z
    end

    function AARTanker.setDefaultTrackHeading(newHeading)
        DEFAULT_TRACK_HEADING = newHeading
    end
end

--- Debug
    local autoGenData = false
    local spawnNumber = 12
    -- if  AARTanker.DebugMode() and autoGenData then
    if autoGenData then
        timer.scheduleFunction(function (vars,time)
            local alphabet = {
                'A','B','C','D','E',
                'F','G','H','I','J',
                'K','L','M','N','O',
            }
            local TACAN_MODE_TABLE = TACANManager.getChannelModeTable()
            local tankerTypeNames = {}
            for _,name in pairs(AARTanker:getTankerTypeNames()) do
                table.insert(tankerTypeNames,name)
            end
            local params = {}
            params.typeName = tankerTypeNames[math.random(1,#tankerTypeNames)]
            -- params.typeName = 'S-3B Tanker'

            params.groupName = 'test-'..math.random(1,20)
            if math.random(1,10) > 6 then
                params.groupName = nil
            end

            params.speed = math.random(250,300)
            if math.random(1,10) > 6 then
                params.speed = nil
            end

            params.callSign = alphabet[math.random(1,#alphabet)]..alphabet[math.random(1,#alphabet)]..alphabet[math.random(1,#alphabet)]
            if math.random(1,10) > 6 then
                params.callSign = nil
            end

            params.TACAN_channel = math.random(1,60)
            if math.random(1,10) > 6 then
                params.TACAN_channel = nil
            end

            params.TACAN_mode = TACAN_MODE_TABLE.X
            if math.random(1,10) > 5 then
                params.TACAN_mode = TACAN_MODE_TABLE.Y
            end
            if math.random(1,10) > 6 then
                params.TACAN_mode = nil
            end

            params.radio_channel = math.random(20,450)
            if math.random(1,10) > 6 then
                params.radio_channel = nil
            end

            if math.random(1,10) > 7 then
                params = tankerTypeNames[math.random(1,#tankerTypeNames)]
                -- params = 'S-3B Tanker'
            end

            Utils.Debug('params:')
            Utils.Debug(params)
            AARTanker:New(params)

            spawnNumber = spawnNumber - 1
            if spawnNumber <= 0 then return end

            return time + math.random(1,10)
        end,nil,timer.getTime()+5)
    end

